package com.wjc.wjc.web.admin;


import com.wjc.wjc.service.NewService;
import com.wjc.wjc.unity.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class NoticeController {

    @Autowired
    private NewService newService;

    @GetMapping("/admin/notice")
    public String notice(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC)
            Pageable pageable, Model model){
        model.addAttribute("page",newService.listNews(pageable));
        return "admin/notice";
    }

    @GetMapping("/admin/notice/input")
    public String input(Model model){
        model.addAttribute("news",new News());
        return "admin/notice-input";
    }
    @GetMapping("/admin/notice/{id}/input")
    public String inputById(@PathVariable Long id, Model model){
        model.addAttribute("news",newService.getNew(id));
        return "admin/notice-input";
    }


    @PostMapping("/admin/new")
    public String saveNew(News news){
        if (news.getId()==0){
            newService.saveNew(news);
            return "redirect:/admin/notice";
        }else {
            newService.updateNew(news.getId(),news);
            System.out.println(news.getId());
            return "redirect:/admin/notice";
        }
    }

    @GetMapping("/new/{id}/delete")
    public String delete(@PathVariable Long id){
        newService.deleteNew(id);
        return "redirect:/admin/notice";
    }

}
